from rest_framework import serializers

from apps.found_person.enterpriseserializer import RecruitEnterpriseSerializer
# from apps.found_person.enterpriseserializer import RecruitEnterpriseSerializer
from apps.found_person.models import Enterprise
from apps.news.models import Article
from apps.answer.models import Question, Label, Reply
from apps.users.models import User


# 问答answer模型 标签
class LabelSerializers(serializers.ModelSerializer):
    class Meta:
        model=Label
        fields='__all__'


# 问答模型 问题
class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model=Question
        fields='__all__'


# 问答模型 回答
class ReplyUserSerializer(serializers.ModelSerializer):
    class Meta:
        model=Reply
        fields='__all__'


# news模型 文章
class ArticlesSerializer(serializers.ModelSerializer):
    class Meta:
        model=Article
        fields='__all__'


# talk模型 企业
class EnterPriseSerializer(serializers.ModelSerializer):
    recruits=RecruitEnterpriseSerializer(many=True,read_only=True)

    class Meta:
        model=Enterprise
        fields=['id','name','labels','logo','recruits','summary']


# users模型 用户
class UserSerializers(serializers.ModelSerializer):
    labels=LabelSerializers(many=True)
    questions=QuestionSerializer(many=True)
    answer_question=serializers.SerializerMethodField(label='我的回答')
    collected_articles=serializers.SerializerMethodField(label='我的收藏的文章')
    enterpises=EnterPriseSerializer(many=True)

    class Meta:
        model = User
        fields = '__all__'
        # username字段增加长度限制，password字段只参与保存，不在返回给前端，增加write_only选项参数
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            },
        }

    def get_answer_question(self,obj):
        replies=obj.replies.filter(parent__isnull=True, type=2)
        return ReplyUserSerializer(replies, many=True, read_only=True).data

    def get_collected_articles(self,obj):
        articles=obj.collected_articles.all()
        return ArticlesSerializer(articles,many=True,read_only=True).data


# users模型 用户
class UserLikeSerializers(serializers.ModelSerializer):
    user_id = serializers.IntegerField()
    username = serializers.StringRelatedField()

    class Meta:
        model = User
        fields = '__all__'
